package com.pirestupppai.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.bean.FeedItem;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.ui.activity.DetailActivity;
import com.pirestupppai.utils.ImageLoadUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.dialog.PsDialog;
import com.pirestupppai.widgets.view.AddLikeLayout;
import com.pirestupppai.widgets.view.AvatarView;

import java.util.List;

/**
 * 瀑布流
 * 热门求P, 首页模块等
 *
 * @author: xiaoluo
 * @date: 2017-03-17 15:59
 */
public class StaggeredAdapter extends RecyclerView.Adapter<StaggeredAdapter.MyViewHolder> {
    private static final int TYPE_ITEM = 0;
    private static final int TYPE_FOOTER = 1;
    private static final int TYPE_HEADER = 2;

    private Context mContext;
    private List<FeedItem> mList;
    private LayoutInflater mInflater;

    private View mFooterView;
    private View mHeaderView;

    private ScaleAnimation mLikeAnimation = new ScaleAnimation(0f, 1.0f, 0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

    public StaggeredAdapter(Context context, List<FeedItem> list) {
        this.mContext = context;
        this.mList = list;
        this.mInflater = LayoutInflater.from(mContext);

        mLikeAnimation.setDuration(500);
    }

    @Override
    public int getItemViewType(int position) {
        if (mFooterView == null && mHeaderView == null) {
            return TYPE_ITEM;
        }
        if (position == (mHeaderView == null ? mList.size() : mList.size() + 1)) {
            return TYPE_FOOTER;
        }
        if (position == 0 && mHeaderView != null) {
            return TYPE_HEADER;
        }
        return TYPE_ITEM;
    }

    @Override
    public StaggeredAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mFooterView != null && viewType == TYPE_FOOTER) {
            return new MyViewHolder(mFooterView);
        }
        if (mHeaderView != null && viewType == TYPE_HEADER) {
            return new MyViewHolder(mHeaderView);
        }

        View view = mInflater.inflate(R.layout.item_stagger_list, parent, false);
        return new MyViewHolder(view);
    }

    // 让上拉加载底部占据一行
    @Override
    public void onViewAttachedToWindow(MyViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
        if (layoutParams != null && layoutParams instanceof StaggeredGridLayoutManager.LayoutParams) {
            StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) layoutParams;
            int position = holder.getLayoutPosition();
            if (getItemViewType(position) == TYPE_HEADER || getItemViewType(position) == TYPE_FOOTER) {
                // 如果方向是纵向的，视图将充满整个宽度，方向为横向，视图将充满整个高度。
                params.setFullSpan(true);
            }
        }
    }

    @Override
    public void onBindViewHolder(StaggeredAdapter.MyViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_HEADER || getItemViewType(position) == TYPE_FOOTER) {
            return;
        }
        int realPosition = getRealPosition(position);
        holder.setData(holder, realPosition);
    }


    /**
     * 获取列表子项实际位置
     */
    private int getRealPosition(int position) {
//        int position = holder.getLayoutPosition();
        return mHeaderView == null ? position : position - 1;
    }

    @Override
    public int getItemCount() {
        if (mHeaderView != null && mFooterView != null) {
            return mList.size() + 2;
        } else if (mFooterView != null) {
            return mList.size() + 1;
        } else if (mHeaderView != null) {
            return mList.size() + 1;
        } else {
            return mList.size();
        }
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        AvatarView avatarView;
        TextView nickNameTv;
        TextView timeTv;
        ImageView showIv;
        ImageView orignalIv;
        TextView workCountTv;
        TextView descTv;
        ImageView psIv;
        ImageView likeIv;
        RelativeLayout orignalLayout;
        AddLikeLayout mParentLayout;


        public MyViewHolder(View itemView) {
            super(itemView);
            if (itemView == mHeaderView || itemView == mFooterView) {
                return;
            }

            avatarView = (AvatarView) itemView.findViewById(R.id.staggered_avatar);
            nickNameTv = (TextView) itemView.findViewById(R.id.staggered_nickname);
            timeTv = (TextView) itemView.findViewById(R.id.staggered_time);
            workCountTv = (TextView) itemView.findViewById(R.id.staggered_work_count);
            descTv = (TextView) itemView.findViewById(R.id.staggered_desc_tv);
            psIv = (ImageView) itemView.findViewById(R.id.staggered_ps_iv);
            likeIv = (ImageView) itemView.findViewById(R.id.staggered_like_iv);
            orignalIv = (ImageView) itemView.findViewById(R.id.staggered_orignal_image);
            showIv = (ImageView) itemView.findViewById(R.id.staggered_show_image);
            orignalLayout = (RelativeLayout) itemView.findViewById(R.id.staggered_original_layout);

            if (mContext instanceof Activity) {
                mParentLayout = (AddLikeLayout) ((Activity) mContext).findViewById(R.id.add_like_layout);
            }
        }

        void setData(MyViewHolder holder, int position) {

            final FeedItem item = mList.get(position);
            holder.nickNameTv.setText(item.getUser().getNickname());
            holder.avatarView.setUid(item.getUser().getId(), false);
            holder.descTv.setText(item.getDesc());
            holder.timeTv.setText(item.getTpTime());
            if (item.isLiked()) {
                likeIv.setImageResource(R.drawable.ic_like_sel);
            } else {
                likeIv.setImageResource(R.drawable.ic_like);
            }

            if (item.getMedias() == null || item.getMedias().size() == 0) {
                return;
            }
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) holder.showIv.getLayoutParams();
            float width = (float) (Constant.WIDTH_OF_SCREEN - 16 * 4) / (float) 2;
            layoutParams.width = (int) width;
            float height = width / item.getMedias().get(0).getImage_ratio();
            layoutParams.height = (int) height;
            holder.showIv.setLayoutParams(layoutParams);

            ImageLoadUtil.getInstance().loadAvatar(item.getUser().getAvatar(), holder.avatarView);
            ImageLoadUtil.getInstance().loadImage(item.getMedias().get(0).getPathname(), holder.showIv, ImageLoadUtil.LoadOption.LOAD_MEDIUM);

            if (item.getType() == FeedItem.ASK_PS_POST) {
                workCountTv.setVisibility(View.VISIBLE);
                psIv.setVisibility(View.VISIBLE);
                orignalLayout.setVisibility(View.GONE);
                likeIv.setVisibility(View.GONE);
            } else {
                workCountTv.setVisibility(View.GONE);
                psIv.setVisibility(View.GONE);
                orignalLayout.setVisibility(View.VISIBLE);
                likeIv.setVisibility(View.VISIBLE);

                ImageLoadUtil.getInstance().loadImage(item.getParent().getMedias().get(0).getPathname(), holder.orignalIv, ImageLoadUtil.LoadOption.LOAD_CORNER);
            }

            likeIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!item.isLiked()) {
                        item.setLiked(true);
                        likeIv.setImageResource(R.drawable.ic_like_sel);
                        likeIv.startAnimation(mLikeAnimation);
                        mParentLayout.addLikeView();

                        NetworkRequest.getInstance().likeFeed(item.getId(),
                                new TupaiSubscriber(mContext) {

                                    @Override
                                    protected void requestSuccess(Object o) {
                                        Utils.showToast("点赞成功");
                                    }

                                    @Override
                                    protected void requestError(String error) {

                                    }
                                });
                    }
                }
            });

            psIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PsDialog dialog = new PsDialog(mContext, item);
                    dialog.show();
                }
            });

            showIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra(Constant.IntentKey.ID, item.getId());
                    intent.setClass(mContext, DetailActivity.class);
                    mContext.startActivity(intent);
                }
            });

        }
    }

    public void setFooterView(View footerView) {
        mFooterView = footerView;
    }

    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
    }

}
